package com.leo.offer;

/**
 * 替换空格为%20
 * @author xuexiaolei
 * @version 2018年03月01日
 */
public class T04ReplaceSpace {
    public static String replaceSpace(String s){
        if (s == null || s.length()==0){ return s; }
        //统计空格数
        int spaceCount = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i)==' '){ spaceCount++; }
        }
        if (spaceCount == 0){ return s;}
        //替换空格,注意使用字符数组而不是String
        char[] res = new char[s.length()+2*spaceCount];
        int i = res.length-1;
        int j = s.length()-1;
        while (i>=0){
            if (s.charAt(j) == ' '){
                res[i--] = '0';
                res[i--] = '2';
                res[i--] = '%';
                j--;
            }else {
                res[i--] = s.charAt(j--);
            }
        }
        return String.valueOf(res);
    }

    public static void main(String[] args) {
        System.out.println(replaceSpace("we are happy"));
        System.out.println(replaceSpace(""));
        System.out.println(replaceSpace(null));
    }
}
